<?php
/**
 * Created by Veyron
 * User: Vy
 * motto:现在的拼搏 为了更好的明天
 * Class: AdminUser
 * day:  2020/1/15
 * Time: 22:30
 */

namespace app\admin\business;
use app\common\model\mysql\AdminUser as AdminUserModel;
use think\Exception;

class AdminUser
{
    public $adminUserObj;
    public function __construct()
    {
        $this->adminUserObj = new AdminUserModel();
    }

    /**
     * Admin用户登录逻辑
     * login
     * @param $data
     * @return bool|\think\response\Json
     */
    public function login($data){
        try {
            $adminUser = $this->getAdminUserByUsername($data['username']);
            if(!$adminUser){
                throw new Exception('用户不存在');
            }
            //验证密码是否正确
            if (!password_verify($data['password'], $adminUser['password'])) {
                throw new Exception('密码不正确');
            }
            //需要记录到mysql表中
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip'   => request()->ip()
            ];
            $res = $this->adminUserObj->updateById($adminUser['id'], $updateData);
            if (!$res) {
                throw new Exception('登录失败');
            }
        }catch (Exception $e){
            //todo 记录日志 $e->getMessage()
            throw new Exception( $e->getMessage());
        }

        //记录session
        session(config('admin.session_admin'),$adminUser);
        return true;
    }

    /**
     * 根据用户名获取用户信息
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminUserByUsername($username){
        $adminUser = $this->adminUserObj->getAdminUserByUsername($username);
        if (empty($adminUser) && $adminUser->status != config('status.mysql.table_normal')) {
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}
